from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from artmarket.models import Artwork
from artmarket.permissions.artmarket_permission import IsArtistOrReadOnly
from artmarket.serializers import ArtworkSerializer, ArtworkCreateSerializer

from django.db import transaction

from users.models import CustomUser


class ArtworkListView(APIView):
    permission_classes = [IsArtistOrReadOnly]

    def get(self, request):
        artworks = Artwork.objects.all().filter(artist__role=0)
        serializer = ArtworkSerializer(artworks, many=True)
        return Response(data={
            'results': serializer.data
        }, status=status.HTTP_200_OK)

    @transaction.atomic
    def post(self, request):
        serializer = ArtworkCreateSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(data={
                'results': serializer.data
            }, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class ArtworkDetailView(APIView):
    permission_classes = [IsArtistOrReadOnly]

    def get(self, request, pk):
        try:
            artwork = Artwork.objects.get(pk=pk)
            serializer = ArtworkSerializer(artwork)
            return Response(data={
                'results': serializer.data
            }, status=status.HTTP_200_OK)
        except Artwork.DoesNotExist:
            return Response(data={"message": "该作品不存在"}, status=status.HTTP_400_BAD_REQUEST)

    def put(self, request, pk):
        artwork = Artwork.objects.get(pk=pk)
        serializer = ArtworkCreateSerializer(artwork, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(data={
                'results': serializer.data
            }, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk):
        artwork = Artwork.objects.get(pk=pk)
        artwork.delete()
        return Response(data={"message": "删除成功"}, status=status.HTTP_200_OK)


class ArtworkAndArtistView(APIView):

    def get(self, request, artist_id):
        # 判断artist_id是否是艺术家
        user = CustomUser.objects.get(pk=artist_id)
        if user.role != 0:
            return Response(data={"message": "该用户不是艺术家"}, status=status.HTTP_400_BAD_REQUEST)
        artworks = Artwork.objects.all().filter(artist_id=artist_id)
        serializer = ArtworkSerializer(artworks, many=True)
        return Response(data={
            'results': serializer.data
        }, status=status.HTTP_200_OK)
